using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using TimeManager.Domain.Entities;


namespace TimeManager.Web.Models {

    public interface ITaskRepository {
        IQueryable<Task> All { get; }
        IQueryable<Task> AllIncluding(params Expression<Func<Task, object>>[] includeProperties);
        Task Find(int id);
        void InsertOrUpdate(Task task);
        void Delete(int id);
        void Save();
    }

    public class TaskRepository : ITaskRepository {
        TimeManagerWebContext context = new TimeManagerWebContext();

        public IQueryable<Task> All {
            get { return context.Tasks; }
        }

        public IQueryable<Task> AllIncluding(params Expression<Func<Task, object>>[] includeProperties) {
            IQueryable<Task> query = context.Tasks;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Task Find(int id) {
            return context.Tasks.Find(id);
        }

        public void InsertOrUpdate(Task task) {
            if (task.TaskId == default(Int32)) {
                context.Tasks.Add(task); // New entity 
            } else {
                context.Entry(task).State = EntityState.Modified; // Existing entity
            }
        }

        public void Delete(int id) {
            var task = context.Tasks.Find(id);
            context.Tasks.Remove(task);
        }

        public void Save() {
            context.SaveChanges();
        }
    }

}